//
//  IconDownloader.m
//  TableViewCellCustomizeIconDownload
//
//  Created by Kishikawa Katsumi on 10/05/05.
//  Copyright 2010 Kishikawa Katsumi. All rights reserved.
//

#import "IconDownloader.h"

@implementation IconDownloader

@synthesize delegate;
@synthesize indexPathInTableView;
@synthesize imageURL;
@synthesize activeDownload;
@synthesize imageConnection;

#pragma mark

- (void)dealloc {
    [indexPathInTableView release];
    
    [activeDownload release];
    
    [imageConnection cancel];
    [imageConnection release];
    
    [super dealloc];
}

- (void)startDownload {
    self.activeDownload = [NSMutableData data];
    
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
                             [NSURLRequest requestWithURL:imageURL] delegate:self];
    self.imageConnection = conn;
    [conn release];
}

- (void)cancelDownload {
    [self.imageConnection cancel];
    self.imageConnection = nil;
    self.activeDownload = nil;
}

#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.activeDownload appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    self.activeDownload = nil;
    self.imageConnection = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    UIImage *image = [[[UIImage alloc] initWithData:self.activeDownload] autorelease];

    self.activeDownload = nil;
    self.imageConnection = nil;
    
    if (image) {
        if ([delegate respondsToSelector:@selector(iconDownloader:didFinished:)]) {
            [delegate iconDownloader:self didFinished:image];
        }
    }
}

@end
